package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cskaoyan.wordmemorize.common.exception.BusinessException;
import com.cskaoyan.wordmemorize.converter.PayConverter;
import com.cskaoyan.wordmemorize.dao.entity.*;
import com.cskaoyan.wordmemorize.dao.mapper.*;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.app.PayOrderDTO;
import com.cskaoyan.wordmemorize.dto.app.VocPaySaleDTO;
import com.cskaoyan.wordmemorize.request.PageRequest;
import com.cskaoyan.wordmemorize.request.PaySuccessNotifyCommand;
import com.cskaoyan.wordmemorize.request.VocPaySaleCommand;
import com.cskaoyan.wordmemorize.service.UserPayService;
import org.apache.ibatis.executor.BatchExecutorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

/**
 * @author 顾海龙
 * @version 1.0
 */
@Service
public class UserPayServiceImpl extends ServiceImpl<VocPaySaleMapper, VocPaySaleDO> implements UserPayService {

    //pay转换接口
    @Autowired
    PayConverter payConverter;

    //对用户表进行操作mapper
    @Autowired
    UserMapper userMapper;

    //对订单表进行操作的mapper
    @Autowired
    VocPaySaleMapper vocPaySaleMapper;

    //对单词上限进行操作的mapper
    @Autowired
    UserVocBoundStatisticsMapper vocBoundStatisticsMapper;

    //对单词上限插入日志表操作的mapper
    @Autowired
    UserVocBoundLogMapper vocBoundLogMapper;

    //查询商品详细信息的mapper
    @Autowired
    GoodsMapper goodsMapper;

    // APP支付接口(解锁等级，购买单词上限, 购买补签卡)
    @Override
    public PayOrderDTO pay(VocPaySaleCommand command, Long userId) throws BusinessException {
        if (command.getItemType() == 3) {
            UserDO userDO = userMapper.selectById(userId);
            if (userDO.getHasSignCard() != 0) {
                throw new BusinessException("用户已经有补签卡，不能重复购买", 501);
            }
        }
        VocPaySaleDO vocPaySaleDO = payConverter.vocPaySaleCommand2DO(command);
        vocPaySaleDO.setUserId(userId);
        vocPaySaleDO.setStatus(1);
        vocPaySaleMapper.insert(vocPaySaleDO);
        PayOrderDTO payOrderDTO = new PayOrderDTO();
        payOrderDTO.setId(String.valueOf(vocPaySaleDO.getId()));
        payOrderDTO.setTotalAmount(vocPaySaleDO.getPayPrice());
        payOrderDTO.setSubject("购买" + vocPaySaleDO.getItemName());
        return payOrderDTO;
    }


    // APP支付成功接口，我需要我们自己通过postman或者Api Fox模拟支付成功的通知(解锁等级，购买代词上限, 购买补签卡)
    @Override
    public String paySuccess(PaySuccessNotifyCommand command, Long userId) {
        VocPaySaleDO vocPaySaleDO = vocPaySaleMapper.selectById(command.getId());
        if ("TRADE_SUCCESS".equals(command.getTradeStatus())) {
            vocPaySaleDO.setStatus(2);
        }
        //对订单类型进行分类处理
        if (vocPaySaleDO.getItemType() == 1) {
            //订单为单词上限卡
            UserDO userDO = userMapper.selectById(userId);
            GoodsDO goodsDO = goodsMapper.selectById(vocPaySaleDO.getItemId());
            QueryWrapper<UserVocBoundStatisticsDO> userVBSQueryWrapper = new QueryWrapper<>();
            userVBSQueryWrapper.eq("user_id", userId);
            //用户单词上限关系表查询结果
            UserVocBoundStatisticsDO userVocBoundStatisticsDO = vocBoundStatisticsMapper.selectOne(userVBSQueryWrapper);
            //更新购买的单词数量
            userVocBoundStatisticsDO.setPay(userVocBoundStatisticsDO.getPay() + goodsDO.getValue());
            //更新总的单词数量
            userVocBoundStatisticsDO.setTotal(userVocBoundStatisticsDO.getTotal() + goodsDO.getValue());
            //更新可使用单词数量
            userVocBoundStatisticsDO.setAvailable(userVocBoundStatisticsDO.getAvailable() + goodsDO.getValue());
            //向数据库更新数据
            vocBoundStatisticsMapper.updateById(userVocBoundStatisticsDO);
            //插入日志
            UserVocBoundLogDO userVocBoundLogDO = new UserVocBoundLogDO(userId, vocPaySaleDO.getId(), 1, LocalDate.now(), goodsDO.getValue(), goodsDO.getName());
            vocBoundLogMapper.insert(userVocBoundLogDO);
        } else if (vocPaySaleDO.getItemType() == 3) {
            //订单为补签卡
            UserDO userDO = userMapper.selectById(userId);
            userDO.setHasSignCard(1);
            userMapper.updateById(userDO);
        } else {
            //订单为解锁等级卡
            GoodsDO goodsDO = goodsMapper.selectById(vocPaySaleDO.getItemId());
            UserDO userDO = userMapper.selectById(userId);
            userDO.setLevelValue(goodsDO.getValue());
            userDO.setLevelName("LVL" + goodsDO.getValue());
            userMapper.updateById(userDO);
        }
        //对订单的状态进行更新
        vocPaySaleMapper.updateById(vocPaySaleDO);
        return "Success";
    }


    // APP获取支付结果
    @Override
    public Integer queryTradeStatus(Long paySaleId) throws BusinessException {
        VocPaySaleDO vocPaySaleDO = vocPaySaleMapper.selectById(paySaleId);
        if (vocPaySaleDO.getStatus() == 1) {
            throw new BusinessException("请求失败", 500);
        }
        return vocPaySaleDO.getStatus();
    }


    // APP获取购买历史
    @Override
    public PageDTO<VocPaySaleDTO> getPaySaleHistory(Long userId, PageRequest pageRequest) throws BusinessException{
        PageDTO<VocPaySaleDTO> paySaleDTOPageDTO;
        QueryWrapper<VocPaySaleDO> vocPaySaleDOQueryWrapper = new QueryWrapper<>();
        vocPaySaleDOQueryWrapper.eq("user_id", userId);
        //判断是否有关键字匹配
        if (pageRequest.getKeyword() != null){
            vocPaySaleDOQueryWrapper.like("item_name",pageRequest.getKeyword());
        }
        //判断是否要分页
        if (pageRequest.getPageNum() != null && pageRequest.getPageNum() > 0) {
            Page<VocPaySaleDO> page = new Page<>(pageRequest.getPageNum(),pageRequest.getCount());
            Page<VocPaySaleDO> vocPaySaleDOPage = vocPaySaleMapper.selectPage(page, vocPaySaleDOQueryWrapper);
            List<VocPaySaleDO> vocPaySaleDOList = vocPaySaleDOPage.getRecords();
            paySaleDTOPageDTO = payConverter.vocPaySalePage2PageDTO(vocPaySaleDOList,vocPaySaleDOPage.getTotal());
        } else {
            List<VocPaySaleDO> vocPaySaleDOList = vocPaySaleMapper.selectList(vocPaySaleDOQueryWrapper);
            paySaleDTOPageDTO = payConverter.vocPaySalePage2PageDTO(vocPaySaleDOList,(long)vocPaySaleDOList.size());
        }
        return paySaleDTOPageDTO;
    }
}

